<!--
 * @Description: 
 * @Version: 0.0
 * @Author: taosong
 * @Date: 2023-04-02 19:04:39
 * @LastEditors: taosong
 * @LastEditTime: 2023-04-02 22:08:57
-->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta
      http-equiv="X-UA-Compatible"
      content="IE=edge"
    />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1.0"
    />
    <title>贪吃蛇</title>
    <script src="../libs//index.js"></script>
    <style>
      * {
        margin: 0;
        padding: 0;
      }
      canvas {
        background-color: yellow;
        margin: 0 auto;
        display: block;
      }
    </style>
  </head>
  <body>
    <canvas
      id="canvas"
      width="600"
      height="600"
      >此浏览器不支持canvas</canvas
    >
    <script>
      /** @type {HTMLCanvasElement} */
      const ctx = document.getElementById('canvas')
      const gl = ctx.getContext('webgl')
      const VERTEX_SHADER_SOURCE = `
        attribute vec4 aPosition;
        void main() {
          gl_Position = aPosition;
          gl_PointSize = 10.0;
        }
      `
      const FRAGMENT_SHADER_SOURCE = `
        void main() {
          gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
        }
      `

      const program = initShader(
        gl,
        VERTEX_SHADER_SOURCE,
        FRAGMENT_SHADER_SOURCE
      )

      const aPosition = gl.getAttribLocation(program, 'aPosition')
      const { x_, y_ } = getRandomPosition()
      gl.vertexAttrib2f(aPosition, x_, y_)
      gl.drawArrays(gl.POINTS, 0, 1)
      let points = []
      ctx.onclick = function (e) {
        const x = e.clientX
        const y = e.clientY
        const { top, left } = ctx.getBoundingClientRect()
        const domY = y - top
        const domX = x - left
        const halfWidth = ctx.offsetWidth / 2
        const halfHeight = ctx.offsetHeight / 2
        const clickX = (domX - halfWidth) / halfWidth
        const clickY = (halfHeight - domY) / halfHeight
        if (points.length > 60) {
          points.shift()
        }
        points.push({
          clickX,
          clickY
        })
        for (let value of points) {
          gl.vertexAttrib2f(aPosition, value.clickX, value.clickY)
          gl.drawArrays(gl.POINTS, 0, 1)
        }
      }

      function getRandomPosition() {
        const x = Math.random().toFixed(1)
        const y = Math.random().toFixed(1)
        let x_
        let y_
        if ((x % 2).toString().length > 2) {
          x_ = x
        } else {
          x_ = -x
        }
        if ((y % 2).toString().length > 2) {
          y_ = y
        } else {
          y_ = -y
        }
        return {
          x_,
          y_
        }
      }
    </script>
  </body>
</html>
